package cn.ipanel.bigdata.dw

import cn.ipanel.bigdata.boot.config.Configuration
import cn.ipanel.bigdata.comm.Parameter.DWD_DB_NAMESPACE
import cn.ipanel.bigdata.dw
import cn.ipanel.bigdata.dw.ods.AbsOdsTable
import cn.ipanel.bigdata.utils.Dictionary.NONE
import cn.ipanel.bigdata.utils.Util
import org.apache.spark.sql.Row

/**
 * Author: lzz
 * Date: 2022/3/24 19:02
 */
package object dwd {

  final lazy val BUILD: String = "create database if not exists " + DWD_DB_NAME
  final lazy val DWD_DB_NAME: String = Configuration.getParam(DWD_DB_NAMESPACE)


  final lazy val Tables: Seq[AbsDwdHive] = {
    Seq()
  }

  trait DwdBasicColumnDefine {

    final val F_COUNT       : String = "f_count"        // 次数，本层的次数，必须默认为1（当然也可以是计算后的值）
    final val F_DURATION    : String = "f_duration"     // 时长，本层的时长，是计算后的值，没有是0，单位毫秒
  }

  abstract class AbsDwdHive(tbName: String, dbName: String = DWD_DB_NAME)
          extends ods.AbsOdsHive(tbName, dbName)
            with DwdBasicColumnDefine {

    def createTable: AbsDwdTable

    override def getTBColumns: Seq[String] = {
      Seq(F_DATE_TIME, F_DEVICE_ID, F_REGION) ++ extraColumnNames ++ Seq(F_COUNT, F_DATE)
    }

    override def buildTable: String = {
      s"""
         | CREATE TABLE IF NOT EXISTS $getDBName.$getTBName (
         |   $F_DATE_TIME STRING,
         |   $F_DEVICE_ID STRING,
         |   $F_REGION STRING,
         |   $extraColumnBuild,
         |   $F_COUNT BIGINT
         | )
         | PARTITIONED BY($F_DATE INT)
         | ROW FORMAT DELIMITED FIELDS TERMINATED BY $dataRowFormatter
         | MAP KEYS TERMINATED BY $dataMapFormatter
         | STORED AS $storageFormatter
         |""".stripMargin
//      CLUSTERED BY($F_USER, $F_DEVICE) INTO $splitBucketsNums BUCKETS
    }
  }

  abstract class AbsDwdTable(f_date_time: String,
                             f_device_id: String,
                             f_region: String,
                             var f_count: Long,
                             f_extra: Map[String, String],
                             f_date: Int)
          extends AbsOdsTable(f_date_time, f_device_id, f_region, f_extra, f_date)
            with DwdBasicColumnDefine {

    import Util._

    override lazy val _PARAM: Array[Any] = Array(f_time, f_device_id, f_region) ++ toParam ++ Array(f_count,
      f_extra, f_date)

    override def _init_(row: Row): AbsDwdTable = {
      super._init_(row)
      f_count       = rowTo[Long](row, F_COUNT, LONG0)
      this
    }
  }
}